<!-- https://docs.camunda.org/manual/latest/reference/bpmn20/gateways/sequence-flow/ -->
<template>
  <Base :moddle="moddle" :bo="bo" @write="write">
    <CollapseItem v-if="typeVisible && conditionVisible" slot="custom" title="Condition">
      <template #content>
        <FormItemSelect
          v-model="conditionType"
          :options="conditionTypes"
          label="Condition Type"
          @change="writeCondition({})"
        />
        <Condition v-model="bo" :condition-type="conditionType" @save-condition="writeCondition" />
      </template>
    </CollapseItem>
  </Base>
</template>

<script>
import Base from '../embbed/Base'
import Condition from '../part/detail/Condition'
import CollapseItem from '../ui/CollapseItem'
import FormItemSelect from '../ui/FormItemSelect'
import elementHelper from '../../mixins/elementHelper'
import { customize, isConditionalSource } from '../../utils'
import { createFormalExpression } from '../../utils/creators'
import { CONDITION_TYPES } from '../../utils/constants'

export default {
  name: 'SequenceFlow',
  components: {
    Base,
    Condition,
    CollapseItem,
    FormItemSelect
  },
  mixins: [elementHelper],
  data() {
    return {
      conditionTypes: CONDITION_TYPES,
      conditionType: ''
    }
  },
  computed: {
    typeVisible() {
      return isConditionalSource(this.element.source)
    },
    conditionVisible() {
      return this.propertyVisible('conditionExpression')
    }
  },
  created() {
    this.sync()
  },
  methods: {
    sync() {
      const condition = this.bo.conditionExpression
      if (condition) {
        if (condition.language) {
          this.conditionType = 'script'
          this.bo.scriptFormat = condition.language
          if (condition.body) {
            this.bo.scriptType = 'script'
            this.bo.config = condition.body
          } else {
            this.bo.scriptType = 'resource'
            this.bo.config = condition.resource
          }
        } else {
          this.conditionType = 'expression'
          this.bo.config = condition.body
        }
      }
    },
    writeCondition(obj) {
      let props
      if ('expression' in obj && obj.expression) {
        props = createFormalExpression(this.moddle, { body: obj.expression })
      } else if ('script' in obj && obj.script) {
        props = createFormalExpression(this.moddle, {
          language: obj.scriptFormat,
          body: obj.script
        })
      } else if ('resource' in obj && obj.resource) {
        props = createFormalExpression(this.moddle, {
          language: obj.scriptFormat,
          [ customize('resource') ]: obj.resource
        })
      }
      this.write({ conditionExpression: props })
    }
  }
}
</script>
